/**
 * Create Common UserInterface With GridForm Style  
 * 
 * Usage : Ext.create('Bleext.abstract.GridForm',[ {columnConfig:[],formConfig:[] }]);
 * @author naluv125@hotmai.com
 */
Ext.define("Bleext.abstract.GridForm",{
	extend		: "Ext.panel.Panel",
	
	 requires: [
	            'Ext.grid.*',
	            'Ext.form.*',
	            'Ext.data.Store',
	            'Ext.selection.CheckboxModel',
	            'Ext.window.MessageBox'
	        ],
    
    frame: true,
	
    layout: {
         type: 'vbox',
         align: 'stretch'
     },

  // None complex configs (booleans, integers, strings) go here
     gridTitle : '/',
     formTitle:'/',
     loadGridUrl:'/loadUrl',
     itemsPerPage: 20,  //items per page
     pageLoad:false, 		//load page when window show up
     formColumnCount:3, //default separate form to 3 columns 
     addUrl: '/addUrl',	//add record
     updateUrl : '/updateUrl',	//load record
     removeUrl:'/removeUrl',	//remove records
     gridColumnCount:3,
     
 	initComponent	: function(config){
 		Ext.apply(this, config);
 		var me = this;
        this.callParent(arguments);
        var form = this.buildFormUI();
        var grid = this.buildGridUI();
        
        me.add(form);
        me.add(grid);
	},
	
	buildGridStore:function(){
		var fields = [];
        for (var i = 0; i < this.columnConfig.length; i++) {
            var col = this.columnConfig[i];
            if(col){
            	 col['name'] = col.dataIndex;
                 fields.push(col);
            }
        }
		var store = Ext.create('Ext.data.Store', {
		    autoLoad: false,
		    fields: fields,
		    pageSize: this.itemsPerPage, 
		    proxy: {
		        type: 'ajax',
		        url:  this.loadGridUrl,
		        reader: {
		            type: 'json',
	            	root : 'result',			//ruled by Pagination.class
	                totalProperty : 'totalRecords'	//ruled by Pagination.class
		        }
		    },
		    remoteSort: true 
		    //sorters: {property: 'due', direction: 'ASC'}  //默认排序
		});
		
		if(this.pageLoad){
			store.load({
			    params:{
			        start:0,
			        limit: this.itemsPerPage
			    }
			});
		}
		
		return store;
	},
	
	buildGridColumn:function(){
		  var columns = [];
		  for (var i = 0; i < this.columnConfig.length; i++) {
	            var col = this.columnConfig[i];
	            if(!col || col.hideGrid === true){
	            	continue;
	            }
	            columns.push(col);
	        }
		  return columns;
	},
	
     buildGridUI:function(){
    	 var store = this.buildGridStore();
    	 var column = this.buildGridColumn();
    	 var selModel = Ext.create('Ext.selection.CheckboxModel', {
    	        listeners: {
    	            selectionchange: function(sm, selections) {
    	            	this.grid.down('#removeButton').setDisabled(selections.length === 0);
    	            	this.grid.down('#editButton').setDisabled(selections.length === 0);
    	            },
    	            scope : this
    	        }
    	    });
    	 this.grid = Ext.create('Ext.grid.Panel', {
    		    title: this.gridTitle,
    		    store: store,
    		    columns: column,
    		    selModel: selModel,
    		    height: 400,
    		    width: 400,
    		    dockedItems: [{
    		        xtype: 'pagingtoolbar',
    		        store: store,   
    		        dock: 'bottom',
    		        displayInfo: true,
    		        displayMsg: '显示 {0} - {1} 条，共 {2} 条记录'
    		    },{
    		    	 xtype: 'toolbar',
    		            items: [{
    		            	itemId: 'addButton',
    		                text:'添加',
    		                tooltip:'添加一条记录',
    		                iconCls:'add',
    				        handler: function() {
    				             this.showUpDlg('add');
    				        },
    				        scope: this
    		            }, '-', {
    		            	itemId: 'editButton',
    		                text:'修改',
    		                tooltip:'修改选中的记录',
    		                iconCls:'my_edit',
    		                disabled: true,
    				        handler: function() {
    				        	this.showUpDlg('edit');
    				        },
    				        scope: this
    		            },'-',{
    		                itemId: 'removeButton',
    		                text:'删除',
    		                tooltip:'删除选中的记录',
    		                iconCls:'remove',
    		                disabled: true,
    				        handler: function() {
    				            this.removeDlg();
    				        },
    				        scope: this
    		            }]
    		    }]
    		});
    	 return this.grid;
     },
	
     /*弹出删除对话框*/
     removeDlg:function(){
    	 var me = this;
    	 Ext.MessageBox.confirm('提示', '你确定要删除所选的记录吗?', function(buttonId ,text ,opt){
    		 var recList = me.grid.getSelectionModel().getSelection();
    		 var sendListIds = [];
    		 for(var i=0;i<recList.length;i++){
    			 sendListIds.push(recList[i].get('id'));
    		 }
    		  if(buttonId == 'yes'){
    			  Ext.Ajax.request({
    				    url: me.removeUrl,
    				    params: {
    				        ids: sendListIds
    				    },
    				    success: function(response){
	    				        var text = response.responseText;
	    				        me.grid.getStore().reload();
	    				        if(text.mesage){
	    				        	Ext.Msg.alert('提示',text.mesage);
	    				        }else{
	    				        	Ext.Msg.alert('提示','删除成功!');
	    				        }
    				    }
    				});
    		  }
    	 });
    	 
     },
     
     /*弹出新增或者编辑对话框*/
     showUpDlg:function( flag ){
    	 
    	 var recList = this.grid.getSelectionModel().getSelection();
    	 if(flag=='edit' && recList.length > 1){
    		 Ext.Msg.alert('提示','编辑时只能选中一条记录');
    		 return ;
    	 }
    	 
    	 var myTitle = (flag=='add'?'新增面板' : '修改面板');  		//title
    	 var items = this.buildDlgItems(flag); 		//items
    	 var url = (flag == 'add'?this.addUrl : this.updateUrl);		//url

    	 var showformpanel  = Ext.create('Ext.form.Panel', {
    		 		header : false,
	    	        bodyStyle: 'padding:5px 5px 0',
	    	        layout: {
	    		        type: 'table',
	    		        columns: this.gridColumnCount
	    	        	/*type : 'column',
	    	        	cloumnWidth : '0.3'*/
	    		    },
	    	        width: 900,
	    	        defaults: {
	    	            border: false,
	    	            xtype: 'textfield'
	    	        },
	    	        fieldDefaults: {
	    	            labelAlign: 'top',
	    	            msgTarget: 'side',
	    	            labelWidth: 75
	    	        },
	    	        url : url,
	    	        items:  items,
	    	        listeners:{
	    	        	beforerender :function(){  
	    	        		if(flag == 'edit'){   //Load Record
	    	        	   		var rec = this.grid.getSelectionModel().getSelection()[0];
	    	        	   		showformpanel.getForm().loadRecord(rec);
	    	        		}
	    	        	},
	    	        	scope : this
	    	        }
    	    });
    	 
    	 this.showWin = Ext.create('Ext.window.Window', {
		    		    title: myTitle,
		    		    width: 1000,
		    		    modal : true,
		    		    layout: {
		    		        type: 'fit'
		    		    },
		    		    items: showformpanel,
		    		    buttonAlign:'center',
		    		    buttons: ['->', {
		    	            text: '确定',
		    	            handler : function(){
		    	            	var me = this;
		    	            	var form = showformpanel.getForm();
		    	            	 if (form.isValid()) {
		    	                     form.submit({
		    	                         success: function(form, action) {
		    	                        	if(action.result.message){
		    	                        		Ext.Msg.alert('提示', action.result.message);
		    	                        		return;
		    	                        	}
		    	                        	 me.grid.getStore().reload();
		    	                        	 me.showWin.close();
		    	                         },
		    	                         failure: function(form, action) {
		    	                             Ext.Msg.alert('Failed', action.result.message);
		    	                         }
		    	                     });
		    	                 }
		    	            },
		    	            scope : this
		    	        }, {
		    	            text: '取消',
		    	            handler : function(){
		    	            	this.up('window').close();
		    	            }
		    	        }]
		    		});
    	 this.showWin.show();
     },
     
     buildDlgItems: function(flag) {
     	var items = [];
         for (var i = 0; i < this.columnConfig.length; i++) {
             var col = this.columnConfig[i];
             if (col.hideForm == flag || col.hideForm == "all") {
                 continue;
             }
             col['fieldLabel'] = col.header;
             if(col.fieldtype) 
            	 col.xtype = col.fieldtype;
             if(col.uneditable && flag == "edit"){
            	 col.readOnly = true;
             }else{
            	 col.readOnly = false;
             }
             items.push(col);
         }
         return items;
     },
     
     
	buildFormUI:function(){
		this.form = Ext.create('Ext.form.Panel', {
		    title: this.formTitle,
		    bodyPadding: 5,
		    width: 350,
		    url: this.loadGridUrl,
		    layout: {
		        type: 'table',
		        columns: this.formColumnCount
		    },
		    fieldDefaults: {
	            msgTarget: 'side',
	            labelAlign:'right',
	            labelWidth: 75
	        },
	        buttonAlign:'center',
		    defaultType: 'textfield',
		    items: this.formConfig,
		    buttons: [{
		        text: '重置',
		        handler: function() {
		            this.up('form').getForm().reset();
		        }
		    }, {
		        text: '查询',
		        formBind: true, //only enabled once the form is valid
		        disabled: true,
		        handler: function() {
		            var form = this.form.getForm();
		            if (form.isValid()) {
                    	var store =  this.grid.getStore();
                    	store.filters.clear();
                    	var extraParms = form.getFieldValues(); 
                    	store.loadPage( 1, {
                			  params:extraParms
                		});
		            }
		        },
		        scope: this
		    }]
		});
		return this.form;
	}
     
});